package own.stu.jobgib.playown.vediodown.common.service;

import own.stu.jobgib.playown.vediodown.bili.model.media.MediaData;
import own.stu.jobgib.playown.vediodown.bili.model.seasons.SeasonArchive;
import own.stu.jobgib.playown.vediodown.bili.service.DownloadService;
import own.stu.jobgib.playown.vediodown.common.config.DefaultConfig;
import own.stu.jobgib.playown.vediodown.common.model.BaseDataInfo;
import own.stu.jobgib.playown.vediodown.webo.model.WaterFallContent;
import own.stu.jobgib.playown.vediodown.webo.service.DownLoadService;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.IntStream;

import static own.stu.jobgib.playown.vediodown.common.service.BaseDownloadService.cookies_path;

public class ManageService {

    private DefaultConfig cfg;

    private BaseDownloadService downloadService;
    private QueueService queueService;
    private ItemQueryService queryService;

    public ManageService(DefaultConfig cfg) {
        this.cfg = cfg;
        queueService = new QueueService();
    }

    public <M, P, T extends BaseDataInfo<M, P>> void service(String baseUrl, Long userId, Class<T> clazz, String cookies) {
        queueService.start();
        queryService.getItemList(baseUrl, clazz, () -> cookies);
    }

    public static void main_2(String[] args) throws IOException, InterruptedException {

        DefaultConfig cfg = new DefaultConfig();
//        WeiboConfig cfg = new WeiboConfig();
        ManageService service = new ManageService(cfg);

//        service.testSeasonArchive();
//        service.testGetWaterFallContent();

//        service.testMediaData();

        TimeUnit.MINUTES.sleep(10);
        service.destory();
    }

    public static void main(String[] args) {
        ManageService.loadPsOnly("https://www.bilibili.com/video/BV1Xh411S7bP", 89, 143);
    }

    private static void loadPsOnly(String baseUrl, int start, int end) {

        ExecutorService service = Executors.newFixedThreadPool(6);


        IntStream.range(start, end + 1).forEach(v -> {
            service.submit(() -> {
                String tmpUrl = baseUrl + "?p=" + v;

                BaseDownloadService.process("yt-dlp",
                        "-P " + "/Users/qim/Downloads/scala",
//                "-o",
//                baseUrl,
                        "--cookies-from-browser", "chrome:" + cookies_path,
                        tmpUrl);
            });
        });

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
        }
        service.shutdown();

    }

    private void initBili(Long userId, Integer initId) {
        initBili(userId, initId, null);
    }

    private void initBili(Long userId, Integer initId, Function filter) {
        downloadService = new DownloadService(cfg, userId);
        queryService = new ItemQueryService(cfg, queueService, downloadService);
        if (initId != null)
            queryService.setInitIdx(userId + "", initId);
        if (filter == null) {

        }
    }

    private void initWeibo(Long userId) {
        downloadService = new DownLoadService(cfg, userId);
        queryService = new ItemQueryService(cfg, queueService, downloadService);
    }

    private void testMediaData() {
        Long userId = 3493140465978044L;
        initBili(userId, 92);
        String url = MediaData.getUrl(userId, 100);
        MediaData.setItemFilter((item) -> !item.getBvId().equals("BV1694y1N73X"));
        service(url, userId, MediaData.class,
                "buvid3=91F9E608-C8BA-21CA-EE39-26D9B14EB07434734infoc; b_nut=1678351134; _uuid=9BD681410-2FE5-AFB5-710103-B6FBB94D414135033infoc; buvid4=ABEEBA7A-252A-8AA0-C872-3AF9E88A18B836074-023030916-jMUoPae2vejbN4MALaSPgw%3D%3D; rpdid=|(J|J|luYJYl0J'uY~)Jl~)mu; nostalgia_conf=-1; hit-dyn-v2=1; LIVE_BUVID=AUTO2216784469803026; i-wanna-go-back=-1; b_ut=5; buvid_fp_plain=undefined; CURRENT_PID=e75c4fa0-cd14-11ed-a7d2-a7828328f196; FEED_LIVE_VERSION=V8; hit-new-style-dyn=1; iflogin_when_web_push=1; go-back-dyn=1; CURRENT_BLACKGAP=0; enable_web_push=ENABLE; header_theme_version=CLOSE; is-2022-channel=1; DedeUserID=384008796; DedeUserID__ckMd5=be6ec5898f138ed9; home_feed_column=4; CURRENT_QUALITY=80; SESSDATA=94e54935%2C1721565172%2C76618%2A12CjCttSqjTa7KG8h3Raw8DK5XnrTYQniayBb7qeZhuPDOFQx-73DdFIn1t6jq5gf0oIUSVjNyS3JwQzRzLWE0a2ZvclRwMHNOV2ExUm9yTkxWTGlKVURsYVJYcEZSdkpCcDFjal9jcW5XQnNlcXJnQ2NxWjdqRmxvSmxMcTVtaDN2WjE5SWtlVWlBIIEC; bili_jct=17c7b98468b35317a2cf7270bd4538e2; sid=78o3ku8r; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDYzMjc2ODksImlhdCI6MTcwNjA2ODQyOSwicGx0IjotMX0.0hhB-M1FwJSZsHCpcpC7rixbE4TuNrs3-NL79_OSm9Q; bili_ticket_expires=1706327629; CURRENT_FNVAL=4048; fingerprint=1b3e7659619970f2ef14aa972b5c206a; buvid_fp=1b3e7659619970f2ef14aa972b5c206a; share_source_origin=COPY; bsource=share_source_copy_link; browser_resolution=1299-725; bp_video_offset_384008796=890776762678509601; PVID=1; b_lsid=CFAA3510C_18D44297694");
    }

    private void testSeasonArchive() {
        Long userId = 510805858L;
        Long seasonId = 58426L;
        int pageSize = 30;
        initBili(userId, null);

        String url = SeasonArchive.getUrl(userId, seasonId, pageSize);
        service(url, userId, SeasonArchive.class,
                "buvid3=91F9E608-C8BA-21CA-EE39-26D9B14EB07434734infoc; b_nut=1678351134; _uuid=9BD681410-2FE5-AFB5-710103-B6FBB94D414135033infoc; buvid4=ABEEBA7A-252A-8AA0-C872-3AF9E88A18B836074-023030916-jMUoPae2vejbN4MALaSPgw%3D%3D; rpdid=|(J|J|luYJYl0J'uY~)Jl~)mu; nostalgia_conf=-1; hit-dyn-v2=1; LIVE_BUVID=AUTO2216784469803026; i-wanna-go-back=-1; b_ut=5; buvid_fp_plain=undefined; CURRENT_PID=e75c4fa0-cd14-11ed-a7d2-a7828328f196; FEED_LIVE_VERSION=V8; hit-new-style-dyn=1; iflogin_when_web_push=1; go-back-dyn=1; CURRENT_BLACKGAP=0; enable_web_push=ENABLE; header_theme_version=CLOSE; is-2022-channel=1; DedeUserID=384008796; DedeUserID__ckMd5=be6ec5898f138ed9; CURRENT_QUALITY=80; browser_resolution=1299-725; home_feed_column=4; fingerprint=1b3e7659619970f2ef14aa972b5c206a; CURRENT_FNVAL=4048; share_source_origin=COPY; bsource=search_baidu; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDM3NTk2NTAsImlhdCI6MTcwMzUwMDM5MCwicGx0IjotMX0.83xhqwfGnUaVUr13pMAFmQ7XgvofdOnljpuvuKb1LI0; bili_ticket_expires=1703759590; buvid_fp=1b3e7659619970f2ef14aa972b5c206a; SESSDATA=48936d54%2C1719200828%2C7b116%2Ac2CjAxEZwbsBuKWHQAgsYpY1uoInC7wa77CNnJw3O209JjQnyAWFPGLBR4GEoWLeAGkt8SVkdCYk9tQU9xdmlFb0RyNEZTbTJuYm5IcFJxVUhoRmxpTWNZbXR5UzBkdXRRLXhHUXFmaE5ieTF4a1ZrLWJOT2ZIWTV4dGljclAzcm12MWxYbWpfSHZRIIEC; bili_jct=178a6a8df39d717ecf1214568fb7fd82; sid=63v4uv4i; b_lsid=1EEB739D_18CAEA3ED5C; PVID=2; bp_video_offset_384008796=880038695874330630");
    }

    private void testGetWaterFallContent() {
        Long userId = 5234280855L;
        initWeibo(userId);

        String url = WaterFallContent.getUrl(userId, "0");
        service(url, userId, WaterFallContent.class,
                "SINAGLOBAL=3503747394057.302.1678590897214; SCF=At-iBpG2IGyQ_2HfLUi7Nf88g8IWw6jgMmPz0igOhYcNOxaztygClDK3Is7kKrHGfYJYXneC1eYSWdUul3-Pxe8.; UOR=,,cn.bing.com; _s_tentry=-; Apache=4064063027517.0063.1702286788322; ULV=1702286788325:9:1:1:4064063027517.0063.1702286788322:1698074085452; XSRF-TOKEN=lyBHBT1pkt0Uo73HZzsiSjlB; login_sid_t=dec9f2a05073c32974699c0fc10d6ecc; cross_origin_proto=SSL; SSOLoginState=1703468170; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WhQq1epVhGxJU7HAXAN5j825NHD95QpS0-pSo2pShzfWs4Dqcjdi--RiK.7i-2Ni--4iKL2iK.ci--fiKnci-zE; SUB=_2A25IjRlcDeRhGedJ7lMX8S_IyTmIHXVr4xSUrDV8PUJbmtAGLXjzkW9NUeBq0xCz6ldF-j37teuRBpwIABVKRhGy; ALF=1706096140; WBPSESS=HRsQ-3pQNdFRfLXEGcltKRXXulQwMjoV2__zqN2JY4CQV8p3Crv1b__jGt6ojoFI2VVtwYRTzkoUbD_lS7fm2LBQnGAX1wq7hAXRtltyhzVT_w-4HAVW7dt7lmMGHJRJSSemmnR7KUX3cUGjrFaSZg==; PC_TOKEN=4589051c50");
    }

    private void destory() throws IOException, InterruptedException {

        while (queueService.hasTasks()) {
            TimeUnit.SECONDS.sleep(2);
        }

        cfg.destory();
        queueService.destory();
    }
}
